package com.orhanobut.hawk;

import static com.orhanobut.hawk.HawkBuilder.STORAGE_TAG_DO_NOT_CHANGE;

import com.orhanobut.hawk.inf.Storage;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

final class SharedPreferencesStorage implements Storage {
    private final Preferences preferences;
    private DatabaseHelper databaseHelper;

    SharedPreferencesStorage(Context context, String tag) {
        databaseHelper = new DatabaseHelper(context); // context 入参类型为 ohos.app.Context
        preferences = databaseHelper.getPreferences(tag);
    }

    SharedPreferencesStorage(Preferences preferences) {
        this.preferences = preferences;
    }

    @Override
    public <T> boolean put(String key, T value) {
        HawkUtils.checkNull("key", key);
        preferences.putString(key, String.valueOf(value));

        return preferences.flushSync();
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T get(String key) {
        return (T) preferences.getString(key, null);
    }

    @Override
    public boolean delete(String key) {
        preferences.delete(key);

        return true;
    }

    @Override
    public boolean contains(String key) {
        return preferences.hasKey(key);
    }

    @Override
    public void flush() {
        preferences.flush();
    }

    @Override
    public boolean destroyPreference() {
        if (databaseHelper != null) {
            return databaseHelper.deletePreferences(STORAGE_TAG_DO_NOT_CHANGE);
        }
        return false;
    }

    @Override
    public boolean deleteAll() {
        preferences.clear();
        return true;
    }

    @Override
    public long count() {
        return preferences.getAll().size();
    }
}
